package com.eduhzy.ttw.work.mvp.presenter;

import android.app.Application;

import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.SPUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.eduhzy.ttw.commonres.utils.RxUtil;
import com.eduhzy.ttw.commonsdk.core.Constants;
import com.eduhzy.ttw.commonsdk.entity.CommonData;
import com.eduhzy.ttw.commonsdk.holder.AutoBaseViewHolder;
import com.eduhzy.ttw.work.mvp.contract.WorkHomeContract;
import com.eduhzy.ttw.work.mvp.model.entity.WorkListData;
import com.jess.arms.di.scope.ActivityScope;
import com.jess.arms.http.imageloader.ImageLoader;
import com.jess.arms.integration.AppManager;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.utils.RxLifecycleUtils;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;
import me.jessyan.rxerrorhandler.handler.RetryWithDelay;


/**
 * @author xubo
 * @date 2018-12-1 15:42:29
 */
@ActivityScope
public class WorkHomePresenter extends BasePresenter<WorkHomeContract.Model, WorkHomeContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;
    private int page = 1;
    private int pageSize = 10;
    @Inject
    BaseQuickAdapter<WorkListData, AutoBaseViewHolder> mAdapter;

    @Inject
    public WorkHomePresenter(WorkHomeContract.Model model, WorkHomeContract.View rootView) {
        super(model, rootView);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;
    }


    public void list4Teacher(boolean pullToRefresh, int type) {
        if (pullToRefresh) {
            page = 1;
        } else {
            page++;
        }
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("type", type);
        map.put("userId", SPUtils.getInstance().getString(Constants.USERID));
        map.put("pageNo", page);
        map.put("pageSize", pageSize);
        mModel.list4Teacher(map)
                .subscribeOn(Schedulers.io())
                .retryWhen(new RetryWithDelay(2, 3))
                .doOnSubscribe(disposable -> {
                    if (pullToRefresh)
                        mRootView.showLoading();//显示进度条
                }).subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doFinally(() -> {
                    //隐藏下拉刷新的进度条
                    if (pullToRefresh)
                        mRootView.hideLoading();
                })
                //使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<CommonData<List<WorkListData>>>(mErrorHandler) {
                    @Override
                    public void onNext(CommonData<List<WorkListData>> data) {
                        if (data.isResult()) {
                            if (pullToRefresh) {
                                mAdapter.setNewData(data.getData());
                            } else {
                                mAdapter.addData(data.getData());
                            }
                            if (data.getData().size() < pageSize) {
                                mAdapter.loadMoreEnd(true);
                            } else {
                                mAdapter.loadMoreComplete();
                            }
                        } else {
                            if (ObjectUtils.isNotEmpty(data.getMessage())) {
                                mRootView.showMessage(data.getMessage());
                            }
                        }
                        if (ObjectUtils.isEmpty(data.getData()) && ObjectUtils.isEmpty(mAdapter.getData())) {
                            mRootView.setEmptyView();
                        }
                    }

                    @Override
                    public void onError(Throwable t) {
                        if (pullToRefresh) {
                            mRootView.setEmptyView();
                        } else {
                            mAdapter.loadMoreFail();
                        }
                    }
                });
    }

    public void hasWorkSubmit(int workId, int position) {
        QMUITipDialog tipDialog = RxUtil.showLoading(mRootView.getActivity(), "正在删除···");
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("workId", workId);
        map.put("userId", SPUtils.getInstance().getString(Constants.USERID));
        mModel.hasWorkSubmit(map)
                .subscribeOn(Schedulers.io())
                .retryWhen(new RetryWithDelay(2, 3))
                .doOnSubscribe(disposable -> {
                    //显示下拉刷新的进度条
                    tipDialog.show();
                }).subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doFinally(() -> {
                    //隐藏下拉刷新的进度条
                    tipDialog.dismiss();
                })
                //使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<CommonData<Map>>(mErrorHandler) {
                    @Override
                    public void onNext(CommonData<Map> commonData) {
                        if (commonData.isResult()) {
                            if (((boolean) commonData.getData().get("hasWorkSubmit"))) {
                                showDeleteConfirg(map, position);
                            } else {
                                removeWork(map, position);
                            }
                        } else {
                            mRootView.showMessage(commonData.getMessage());
                        }
                    }
                });
    }

    private void showDeleteConfirg(Map<String, Object> map, int position) {
        RxUtil.showConfirmDialog(mRootView.getActivity(), "作业删除", "已经有学生提交，如果删除，学生提交的作业也将一起删除。你确认删除该作业吗？", new QMUIDialogAction.ActionListener() {
            @Override
            public void onClick(QMUIDialog dialog, int index) {
                removeWork(map, position);
                dialog.dismiss();
            }
        });
    }

    public void removeWork(Map<String, Object> map, int position) {
        QMUITipDialog tipDialog = RxUtil.showLoading(mRootView.getActivity(), "正在删除···");
        mModel.removeWork(map)
                .subscribeOn(Schedulers.io())
                .retryWhen(new RetryWithDelay(2, 3))
                .doOnSubscribe(disposable -> {
                    //显示下拉刷新的进度条
                    tipDialog.show();
                }).subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doFinally(() -> {
                    //隐藏下拉刷新的进度条
                    tipDialog.dismiss();
                })
                //使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<CommonData<Map>>(mErrorHandler) {
                    @Override
                    public void onNext(CommonData<Map> commonData) {
                        if (commonData.isResult()) {
                            mAdapter.remove(position);
                            if (mAdapter.getData().size() > position) {
                                mAdapter.notifyItemChanged(position);
                            } else {
                                mAdapter.notifyDataSetChanged();
                            }
                        } else {
                            mRootView.showMessage(commonData.getMessage());
                        }
                    }
                });
    }
}
